package com.thouiot.test.modbus.exception.handler;

import com.thouiot.common.exception.ErrorCodeEnum;
import com.thouiot.common.exception.TiotRuntimeException;
import com.thouiot.common.result.ResultUtil;
import com.thouiot.common.result.TiotResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Optional;

/**
 * @description 全局异常处理
 * @author wangkai
 * @date 2025/04/17 09:22
 */
@Order(-1)  // 优先使用
@RestControllerAdvice
public class ModbusExceptionHandlerAdvice {

    private static final Logger log = LoggerFactory.getLogger(ModbusExceptionHandlerAdvice.class);

    /**
     * 处理自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(TiotRuntimeException.class)
    @ResponseStatus(HttpStatus.OK)
    public TiotResult handleException(TiotRuntimeException e) {
        log.error("控制器错误处理", e);
        return ResultUtil.builderResult(e.getErrorCodeEnum());
    }

    /**
     * 处理所有不可知的异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public TiotResult handleException(Exception e) {
        log.error("控制器错误处理", e);
        Throwable throwable = e.getCause();
        if (throwable instanceof TiotRuntimeException) {
            TiotRuntimeException ex = (TiotRuntimeException) throwable;
            if (ex.getErrorCodeEnum() != null) {
                return ResultUtil.builderResult(ex.getErrorCodeEnum());
            }
            return ResultUtil.builderFailedResult(Optional.ofNullable(e.getMessage()).orElse("未知异常"));
        }
        return ResultUtil.builderResult(ErrorCodeEnum.SERVER_ERROR);
    }
}
